/*
 * Copyright © OpenAtom Foundation.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *      http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package io.iec.edp.caf.msu.client.event;

import io.iec.edp.caf.commons.event.StartupCompletedEvent;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.msu.api.ServiceUnitAwareService;
import io.iec.edp.caf.msu.api.client.ServiceRegistry;
import io.iec.edp.caf.msu.api.entity.MsuProperties;
import io.iec.edp.caf.msu.api.entity.ServiceUnitRegisterInfo;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.context.ApplicationListener;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Leon Huo
 */
@Slf4j
public class ServiceRegistryListener implements ApplicationListener<StartupCompletedEvent> {

    private ServiceRegistry serviceRegistry;

    private MsuProperties msuProperties;

    public ServiceRegistryListener(ServiceRegistry serviceRegistry, MsuProperties msuProperties) {
        this.serviceRegistry = serviceRegistry;
        this.msuProperties = msuProperties;
    }

    @Override
    public void onApplicationEvent(StartupCompletedEvent myEvent) {
        //获取当前应用服务器下的所有SU信息
        var srv = SpringBeanUtils.getBean(ServiceUnitAwareService.class);
        List<String> suInfoList = srv.getEnabledServiceUnits();
        ServiceUnitRegisterInfo serviceUnitRegisterInfo = srv.getServiceUnitRegisterInfo(msuProperties.getApplicationName(),msuProperties.getServiceName(),suInfoList);
        serviceRegistry.register(serviceUnitRegisterInfo);
        log.info("current service register type:"+serviceRegistry.getClass().getName());
        //添加关闭进程的监听事件，停止服务时可以注销su信息
        //当前先通过@PreDestroy注解来
//        addMsuShutDownHooks(serviceUnitRegisterInfo);
    }




    private void addMsuShutDownHooks(ServiceUnitRegisterInfo serviceUnitRegisterInfo){
        Thread shutdown = new Thread(new Runnable() {
            @Override
            public void run() {
                serviceRegistry.unRegister();
            }
        });
        Runtime.getRuntime().addShutdownHook(shutdown);
    }

}

